const { EventEmitter } = require('events')
// 事件的触发器
const eventEmitter = new EventEmitter()

function createData(app){
    const data = new Proxy({
        isRunning: false,
        port: 8080,
    }, {
        get(data, key) {
            return Reflect.get(data, key) // data[key]
        },
        set(data, key, value) {
            const res = Reflect.set(data, key, value) // data[key] = value

            switch (key) {
                case 'isRunning':
                    if (value) {
                        eventEmitter.emit('content', data.port)
                    } else {
                        eventEmitter.emit('close')
                    }
                    break;
                case 'port' :
                    eventEmitter.emit('portChange', data.port)
                    break;
                default :
                    break;
            }
            return res
        }
    })

    eventEmitter.once('content', handleContent)

    eventEmitter.once('close', handleClose)

    eventEmitter.on('portChange', handlePortChange)

    function  handleContent(port) {
        console.log(`Server is running on port ${port} ...`)
    }

    function handleClose() {
        console.log('Serve is Closed')
    }

    function handlePortChange(port) {
        app.close(() => {
            data.isRunning = false

            app.listen(port, () => {
                data.isRunning = true
                console.log(`Server is changed onto port ${port}`)
            })
        })
    }
    return {
        data,
        emitter: eventEmitter
    }
}


module.exports = createData
